package org.csy.work.servlet;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csy.work.dao.ProductDao;
import org.csy.work.dao.impl.ProductDaoImpl;
import org.csy.work.entity.Product;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ZJL
 * @date 2024-11-25
 */
@WebServlet("/updateProduct.do")
public class UpdateProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String productId = req.getParameter("productId");
        String productName = req.getParameter("productName");
        String productType = req.getParameter("productType");
        String productPrice = req.getParameter("productPrice");
        String productCount = req.getParameter("productCount");
        String productDate = req.getParameter("productDate");
        String productSale = req.getParameter("productSale");
        String productDesc = req.getParameter("productDesc");
        String productImg = req.getParameter("productImage");
        String productStatus = req.getParameter("productStatus");
        

        ProductDao productDao = new ProductDaoImpl();
        Product p = productDao.getProductById(productId);
        String message = "";
        if(p != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date d = sdf.parse(productDate);
                p.setProductId(productId);
                p.setProductName(productName);
                p.setProductType(productType);
                p.setProductCount(Integer.parseInt(productCount));
                p.setProductPrice(Double.parseDouble(productPrice));
                p.setProductImage(productImg);
                p.setProductDesc(productDesc);
                p.setProductDate(d);
                p.setProductSale(Integer.parseInt(productSale));
                p.setProductStatus(Integer.parseInt(productStatus));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            int n = productDao.update(p);
            if (n > 0) {
                message = "修改成功";
            }
        }else{
            message = "商品不存在，无法修改";
        }
        PrintWriter out = resp.getWriter();
        out.write(message);
        out.flush();
        out.close();
    }
}
